<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/private-blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/private-blog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/private-blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/private-blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/private-blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/private-blog/images/yy.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/private-blog/images/icon/yy32.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/private-blog/images/icon/yy16.jpg?v=5.1.4">


  <link rel="mask-icon" href="/private-blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="SpringBoot,kaptcha," />










<meta name="description" content="前言后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uu">
<meta name="keywords" content="SpringBoot,kaptcha">
<meta property="og:type" content="article">
<meta property="og:title" content="基于kaptcha实现后端验证码">
<meta property="og:url" content="http:&#x2F;&#x2F;zy0912.gitee.io&#x2F;private-blog&#x2F;2020&#x2F;12&#x2F;21&#x2F;%E5%9F%BA%E4%BA%8Ekaptcha%E5%AE%9E%E7%8E%B0%E5%90%8E%E7%AB%AF%E9%AA%8C%E8%AF%81%E7%A0%81&#x2F;index.html">
<meta property="og:site_name" content="Culaccino&#39;s blog">
<meta property="og:description" content="前言后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uu">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https:&#x2F;&#x2F;gitee.com&#x2F;zy0912&#x2F;Picture-bed&#x2F;raw&#x2F;master&#x2F;img&#x2F;20210517101142.png">
<meta property="og:updated_time" content="2021-05-20T00:56:32.311Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https:&#x2F;&#x2F;gitee.com&#x2F;zy0912&#x2F;Picture-bed&#x2F;raw&#x2F;master&#x2F;img&#x2F;20210517101142.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/private-blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zy0912.gitee.io/private-blog/2020/12/21/基于kaptcha实现后端验证码/"/>





  <title>基于kaptcha实现后端验证码 | Culaccino's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/private-blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Culaccino's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Nothing is impossible！！</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/private-blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/private-blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/private-blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/private-blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zy0912.gitee.io/private-blog/private-blog/2020/12/21/%E5%9F%BA%E4%BA%8Ekaptcha%E5%AE%9E%E7%8E%B0%E5%90%8E%E7%AB%AF%E9%AA%8C%E8%AF%81%E7%A0%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Culaccino">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/private-blog/images/yy.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Culaccino's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">基于kaptcha实现后端验证码</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-21T10:06:33+08:00">
                2020-12-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/private-blog/categories/SpringBoot/" itemprop="url" rel="index">
                    <span itemprop="name">SpringBoot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本页总阅读数<i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><h4 id="后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。"><a href="#后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。" class="headerlink" title="后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。"></a>后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。</h4><a id="more"></a>
<h2 id="后端"><a href="#后端" class="headerlink" title="后端"></a>后端</h2><h3 id="pom-xml-需要依赖"><a href="#pom-xml-需要依赖" class="headerlink" title="pom.xml 需要依赖"></a>pom.xml 需要依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 基于baomidou封装过的kaptcha --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.baomidou<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>kaptcha-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--避免写get，set--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- redis --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="application-yml-配置文件"><a href="#application-yml-配置文件" class="headerlink" title="application.yml 配置文件"></a>application.yml 配置文件</h3><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line"><span class="attr">  port:</span> <span class="number">8080</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  application:</span></span><br><span class="line"><span class="attr">    name:</span> <span class="string">springboot-kaptcha</span></span><br><span class="line">  <span class="comment">#redis配置  </span></span><br><span class="line"><span class="attr">  redis:</span></span><br><span class="line"><span class="attr">    host:</span> <span class="string">localhost</span></span><br><span class="line"><span class="attr">    port:</span> <span class="number">6379</span></span><br><span class="line"><span class="comment">#验证码基础设置    </span></span><br><span class="line"><span class="attr">kaptcha:</span></span><br><span class="line"><span class="attr">  height:</span> <span class="number">50</span></span><br><span class="line"><span class="attr">  width:</span> <span class="number">200</span></span><br><span class="line"><span class="attr">  content:</span></span><br><span class="line"><span class="attr">    length:</span> <span class="number">4</span></span><br><span class="line"><span class="attr">    source:</span> <span class="string">abcdefghjklmnopqrstuvwxyz23456789</span></span><br><span class="line"><span class="attr">    space:</span> <span class="number">2</span></span><br><span class="line"><span class="attr">  font:</span></span><br><span class="line"><span class="attr">    color:</span> <span class="string">black</span></span><br><span class="line"><span class="attr">    name:</span> <span class="string">Arial</span></span><br><span class="line"><span class="attr">    size:</span> <span class="number">40</span></span><br><span class="line"><span class="attr">  background-color:</span></span><br><span class="line"><span class="attr">    from:</span> <span class="string">lightGray</span></span><br><span class="line"><span class="attr">    to:</span> <span class="string">white</span></span><br><span class="line"><span class="attr">  border:</span></span><br><span class="line"><span class="attr">    enabled:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">    color:</span> <span class="string">black</span></span><br><span class="line"><span class="attr">    thickness:</span> <span class="number">1</span></span><br></pre></td></tr></table></figure>

<h3 id="Redis-工具类"><a href="#Redis-工具类" class="headerlink" title="Redis 工具类"></a>Redis 工具类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.example.utils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.redis.core.StringRedisTemplate;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.TimeUnit;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * redis操作Service的实现类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisUtils</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> StringRedisTemplate stringRedisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key   键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> value 值</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(String key, String value)</span> </span>&#123;</span><br><span class="line">        stringRedisTemplate.opsForValue().set(key, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储数据到指定区域</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> region   区域</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> value 值</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(String region, String key, String value)</span> </span>&#123;</span><br><span class="line">        stringRedisTemplate.opsForValue().set(region + <span class="string">":"</span> + key, value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储数据并设置时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> region   区域</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> value 值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expire 过期时间</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(String region, String key, String value, <span class="keyword">long</span> expire)</span> </span>&#123;</span><br><span class="line">        String rKey = region + <span class="string">":"</span> + key;</span><br><span class="line">        stringRedisTemplate.opsForValue().set(rKey, value);</span><br><span class="line">        stringRedisTemplate.expire(rKey, expire, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 值</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">get</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stringRedisTemplate.opsForValue().get(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Description</span>: 通过区域和键获取数据</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Author</span>: zhengyue</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Date</span>: 2020/8/24 15:04</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span>: [region, key]</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Return</span>: java.lang.String</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">get</span><span class="params">(String region, String key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stringRedisTemplate.opsForValue().get(region + <span class="string">":"</span> + key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置超期时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key    键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expire 过期时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 是否成功</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">expire</span><span class="params">(String key, <span class="keyword">long</span> expire)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置区域超期时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key    键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expire 过期时间</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 是否成功</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">expire</span><span class="params">(String region, String key, <span class="keyword">long</span> expire)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stringRedisTemplate.expire(region+<span class="string">":"</span>+key, expire, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除数据</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 键</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        stringRedisTemplate.delete(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除区域数据</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span> region 区域</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 键</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">(String region, String key)</span> </span>&#123;</span><br><span class="line">        stringRedisTemplate.delete(region + <span class="string">":"</span> +key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Description</span>: 删除指定区域的数据</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Author</span>: zhengyue</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Date</span>: 2020/8/24 14:49</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Param</span>: region</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Return</span>:</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">removeRegion</span><span class="params">(String region)</span> </span>&#123;</span><br><span class="line">        Set&lt;String&gt; keys = stringRedisTemplate.keys(region + <span class="string">":*"</span>);</span><br><span class="line">        stringRedisTemplate.delete(keys);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 自增操作</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key   键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> delta 自增步长</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">increment</span><span class="params">(String key, <span class="keyword">long</span> delta)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> stringRedisTemplate.opsForValue().increment(key, delta);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="生成验证码接口"><a href="#生成验证码接口" class="headerlink" title="生成验证码接口"></a>生成验证码接口</h3><h4 id="从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。"><a href="#从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。" class="headerlink" title="从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。"></a>从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(<span class="string">"/render"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">render</span><span class="params">(String uuid)</span> </span>&#123;</span><br><span class="line">  String code = kaptcha.render();</span><br><span class="line">  <span class="comment">// 存入redis</span></span><br><span class="line">  redisUtils.set(uuid, code);</span><br><span class="line">  <span class="comment">// 设定验证码过期时间900s</span></span><br><span class="line">  redisUtils.expire(uuid, <span class="number">60</span>*<span class="number">10</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="校验验证码"><a href="#校验验证码" class="headerlink" title="校验验证码"></a>校验验证码</h3><h4 id="从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。"><a href="#从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。" class="headerlink" title="从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。"></a>从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(<span class="string">"/valid"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Boolean <span class="title">validDefaultTime</span><span class="params">(KaptchaValidDTO dto)</span> </span>&#123;</span><br><span class="line">  String code = <span class="keyword">null</span>;</span><br><span class="line">  code = redisUtils.get(dto.getUuid());</span><br><span class="line">  <span class="comment">// 没有找到key值，或者不等于传递过来的key值，返回验证失败</span></span><br><span class="line">  <span class="keyword">if</span>(StringUtils.isEmpty(code)</span><br><span class="line">          || !code.equals(dto.getCode())) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 验证成功，移除key值</span></span><br><span class="line">  redisUtils.remove(dto.getUuid());</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="前端"><a href="#前端" class="headerlink" title="前端"></a>前端</h2><h3 id="验证码获取"><a href="#验证码获取" class="headerlink" title="验证码获取"></a>验证码获取</h3><h4 id="前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。"><a href="#前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。" class="headerlink" title="前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。"></a>前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;div class=&quot;kaptcha&quot;&gt;</span><br><span class="line">    &lt;img :src=&quot;`http://localhost:8080/kaptcha/render?uuid=` + uuid&quot; alt=&quot;&quot; /&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  data() &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      uuid: &quot;&quot;,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line">      this.uuid = this.uuidRender()</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    // 生成uuid</span><br><span class="line">    uuidRender() &#123;</span><br><span class="line">      var temp_url = URL.createObjectURL(new Blob())</span><br><span class="line">      var uuid = temp_url.toString()</span><br><span class="line">      URL.revokeObjectURL(temp_url)</span><br><span class="line">      return uuid.substr(uuid.lastIndexOf(&quot;/&quot;) + 1)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h4 id="页面成功显示图片"><a href="#页面成功显示图片" class="headerlink" title="页面成功显示图片"></a>页面成功显示图片</h4><p><img src="https://gitee.com/zy0912/Picture-bed/raw/master/img/20210517101142.png" alt=""></p>
<h3 id="刷新二维码"><a href="#刷新二维码" class="headerlink" title="刷新二维码"></a>刷新二维码</h3><h4 id="给img绑定一个点击事件，执行refresh方法"><a href="#给img绑定一个点击事件，执行refresh方法" class="headerlink" title="给img绑定一个点击事件，执行refresh方法"></a>给img绑定一个点击事件，执行refresh方法</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">img</span> @<span class="attr">click</span>=<span class="string">"refresh"</span> <span class="attr">:src</span>=<span class="string">"`http://localhost:8080/kaptcha/render?uuid=` + uuid"</span> <span class="attr">alt</span>=<span class="string">""</span> /&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="通过重新生成uuid来刷新图片链接地址，从而重新请求"><a href="#通过重新生成uuid来刷新图片链接地址，从而重新请求" class="headerlink" title="通过重新生成uuid来刷新图片链接地址，从而重新请求"></a>通过重新生成uuid来刷新图片链接地址，从而重新请求</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 刷新二维码</span></span><br><span class="line">    refresh() &#123;</span><br><span class="line">        <span class="keyword">this</span>.uuid = <span class="keyword">this</span>.uuidRender()</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果你觉得有帮助，慷慨如你，可以扫描下面的二维码赞赏一下</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/yy.jpg" alt="Culaccino 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/yy.jpg" alt="Culaccino 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/private-blog/tags/SpringBoot/" rel="tag"># SpringBoot</a>
          
            <a href="/private-blog/tags/kaptcha/" rel="tag"># kaptcha</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/private-blog/2020/11/02/Minio-%E5%88%86%E5%B8%83%E5%BC%8F%E6%96%87%E4%BB%B6%E5%AD%98%E5%82%A8%E6%96%B9%E6%A1%88-spring-boot%E6%95%B4%E5%90%88/" rel="next" title="Minio 分布式文件存储方案 + spring boot整合">
                <i class="fa fa-chevron-left"></i> Minio 分布式文件存储方案 + spring boot整合
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/private-blog/2021/02/20/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E8%8E%B7%E5%8F%96access-token%EF%BC%8C%E5%B9%B6%E5%AE%9A%E6%97%B6%E5%88%B7%E6%96%B0/" rel="prev" title="微信小程序获取access_token，并定时刷新">
                微信小程序获取access_token，并定时刷新 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/private-blog/images/yy.jpg"
                alt="Culaccino" />
            
              <p class="site-author-name" itemprop="name">Culaccino</p>
              <p class="site-description motion-element" itemprop="description">A glass with a cold drink left a round watermark on the table.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/private-blog/archives">
              
                  <span class="site-state-item-count">40</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/private-blog/categories/index.html">
                  <span class="site-state-item-count">32</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/private-blog/tags/index.html">
                  <span class="site-state-item-count">38</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zhengyue12" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mail.qq.com/" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://info52.top" title="山有木兮" target="_blank">山有木兮</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://dianzihut.com/" title="RE-Empire" target="_blank">RE-Empire</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。"><span class="nav-number">1.0.1.</span> <span class="nav-text">后端引入kaptcha谷歌验证码生成工具，封装成一个接口。前端调用前先生成一个uuid字符串，将这个参数拼在图片的src属性后边，后端获得这个uuid参数，将其存入以uuid为key值，生成的验证码code值为value存入redis，有效期验证10分钟。校验验证码的时候前端将uuid值和code值一起传到后端，后端通过redis查找校验验证码是否正确。一般需求情况下，验证码需要刷新，因为uuid参数是拼在src属性后边，重新生成一个uuid即可完成刷新。</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后端"><span class="nav-number">2.</span> <span class="nav-text">后端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#pom-xml-需要依赖"><span class="nav-number">2.1.</span> <span class="nav-text">pom.xml 需要依赖</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#application-yml-配置文件"><span class="nav-number">2.2.</span> <span class="nav-text">application.yml 配置文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Redis-工具类"><span class="nav-number">2.3.</span> <span class="nav-text">Redis 工具类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生成验证码接口"><span class="nav-number">2.4.</span> <span class="nav-text">生成验证码接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。"><span class="nav-number">2.4.1.</span> <span class="nav-text">从前端获取一个uuid，将uuid和生成的code值以key、value形式存入redis，并设置有效期限。同时返回验证码图片给前端。</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#校验验证码"><span class="nav-number">2.5.</span> <span class="nav-text">校验验证码</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。"><span class="nav-number">2.5.1.</span> <span class="nav-text">从前端获取uuid以及code值，通过redis查找code值是否匹配，匹配成功移除rediskey值。</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#前端"><span class="nav-number">3.</span> <span class="nav-text">前端</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#验证码获取"><span class="nav-number">3.1.</span> <span class="nav-text">验证码获取</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。"><span class="nav-number">3.1.1.</span> <span class="nav-text">前端是基于vue实现的，创建一个img标签用来接收后端生成接口返回的图片，这里还需要有一个uuid。在vue的mounted生命周期方法中先生成uuid值，并拼到图片的src属性后边。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#页面成功显示图片"><span class="nav-number">3.1.2.</span> <span class="nav-text">页面成功显示图片</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#刷新二维码"><span class="nav-number">3.2.</span> <span class="nav-text">刷新二维码</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#给img绑定一个点击事件，执行refresh方法"><span class="nav-number">3.2.1.</span> <span class="nav-text">给img绑定一个点击事件，执行refresh方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通过重新生成uuid来刷新图片链接地址，从而重新请求"><span class="nav-number">3.2.2.</span> <span class="nav-text">通过重新生成uuid来刷新图片链接地址，从而重新请求</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Culaccino</span>

  
</div>

<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>


-->

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js""></script>

  
    <span class="site-uv">
      本站访问数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/private-blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/private-blog/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/private-blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/private-blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/private-blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/private-blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/private-blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/private-blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/private-blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/private-blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
